<?php
namespace app\common\repositories\system;

use app\common\dao\system\SystemRoleDao as dao;
use app\common\repositories\BaseRepository;
use FormBuilder\Factory\Elm;
use FormBuilder\Form;
use think\facade\Route;

/**
 * Class BaseRepository
 * @package common\repositories
 * @mixin dao
 */
class SystemRoleRepository extends BaseRepository
{
    public function __construct(dao $dao)
    {
        $this->dao = $dao;
    }

    public function search(string $type, array $where, $page, $limit)
    {
        $query = $this->dao->search($type, $where);
        $count = $query->count();
        $list = $query->page($page, $limit)->hidden(['update_time'])->select();

        foreach ($list as $k => $role) {
            $list[$k]['rule_name'] = $role->ruleNames();
        }
        return compact('count', 'list');
    }


    public function update(int $id, array $data)
    {
        if (isset($data['rules']))
            $data['rules'] = implode(',', $data['rules']);
        return $this->dao->update($id, $data);
    }


    public function form(string $type, ?int $id = null, array $formData = []): Form
    {
        if ($type == 'admin')
            $form = Elm::createForm(is_null($id) ? Route::buildUrl('systemRoleCreate')->build() : Route::buildUrl('systemRoleUpdate', ['id' => $id])->build());

        $options = app()->make(SystemMenuRepository::class)->getTree($type);
        $form->setRule([
            Elm::input('role_name', '身份名称')->required(),
            Elm::tree('rules', '权限')->data($options)->defaultExpandAll(true)->showCheckbox(true),
            Elm::switches('status', '是否开启', 1)->inactiveValue(0)->activeValue(1)->inactiveText('关闭')->activeText('开启'),
        ]);

        return $form->setTitle(is_null($id) ? '添加身份' : '编辑身份')->formData($formData);
    }


    public function updateForm(string $type, int $id)
    {
        return $this->form($type, $id, $this->dao->get($id)->toArray());
    }
}